package com.pig4cloud.pig.juhe.api.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author: yuwenfeng
 * @Date: 2021/08/09/13:55
 * @Description:
 */

public class SecurityUtils {

	private static String LOGTAG = "SecurityUtils";

	private static final byte[] SECRET_KEY;

	static {
		SECRET_KEY = getMD516(getMD516("DSJFIVJDG845234").substring(3, 12))
				.getBytes();

	}

	/**
	 * @description: 参数排序
	 */
	public static String getSortQueryString(Map<String, Object> params) {
		Object[] keys = params.keySet().toArray();
		Arrays.sort(keys);
		StringBuffer sb = new StringBuffer();
		for (Object key : keys) {
			if (!"sign".equals(key)) {
				if (null != params.get(String.valueOf(key))) {
					sb.append(params.get(String.valueOf(key)));
				}
			}
		}
		return sb.toString();
	}

	/*
	 * MD5加密,返回32位小写
	 */
	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			} else {
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		}
		return md5StrBuff.toString().toLowerCase();
	}

	/*
	 * MD5加密,返回16位大写
	 */
	public static String getMD516(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			} else {
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}

		}
		// // 16位加密，从第9位到25位
		return md5StrBuff.substring(8, 24).toString();
	}

	/**
	 * @description: 生成sign
	 */
	public static String getAppSign(Map<String, Object> params, String appSecret) throws Exception {
		String signString = getSortQueryString(params);
		signString = signString + appSecret;
		System.out.println("signString:" + signString);
		return getMD5Str(signString);
	}

	public static Map<String, Object> toVerifyMap(Map<String, String[]> requestParams) throws UnsupportedEncodingException {
		Map<String, Object> params = new HashMap<>();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
			String name = (String) iter.next();
			String[] values = requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = URLEncoder.encode(valueStr, "utf-8");
			params.put(name, valueStr);
			System.out.println("encodeMap:------ value = " + valueStr);
		}
		return params;
	}

	public static Map<String, String> toVerifyStringMap(Map<String, String[]> requestParams) throws UnsupportedEncodingException {
		Map<String, String> params = new HashMap<>();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
			String name = (String) iter.next();
			String[] values = requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = URLEncoder.encode(valueStr, "utf-8");
			params.put(name, valueStr);
			System.out.println("encodeMap:------ value = " + valueStr);
		}
		return params;
	}

	/**
	 * 聚合回调加密sign
	 */
	public static String getJhPaySign(Map<String, String> params, String appSecret) {
		TreeMap<String, String> signMap = new TreeMap<String, String>(params);
		StringBuilder stringBuilder = new StringBuilder(1024);
		for (Map.Entry<String, String> entry : signMap.entrySet()) {
			if ("sign".equals(entry.getKey())) {
				continue;
			}
			if (entry.getValue() != null) {
				stringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
			}
		}
		stringBuilder.append(appSecret);
		String signSrc = stringBuilder.toString().replaceAll("&", "");//剔除参数中含有的'&'符号
		System.out.println("JhPaySign:" + signSrc);
		return getMD5Str(signSrc);
	}

	public static void main(String[] args) throws Exception {
        /*String appKey = "c51a9906225895f5eabf3c84968712ce";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("req_param_1", "abc123");
        params.put("req_param_2", "---#---?---/---");
        params.put("req_param_3", "");
        params.put("req_param_4", "你好");
        String signature = getAppSign(params, appKey);
        System.out.println("signature：" + signature);*/
        /*Integer num = new Integer(45);
        String amount = BigDecimal.valueOf(num).divide(BigDecimal.valueOf(100D), 2, BigDecimal.ROUND_DOWN).toString();
        System.out.println(amount);*/
        /*Map<String, String> ucSignMap = new HashMap<>();
        ucSignMap.put("cpOrderId", "210814170223522Xx2d2k");
        ucSignMap.put("notifyUrl", "210814170223522Xx2d2k");
        ucSignMap.put("amount", "1.00");
        ucSignMap.put("accountId", "46d98fdd34bd973cf25eab47769196d5");
        String ucSignature = SecurityUtils.getUcSign(ucSignMap, "3265f26913d09592906790e674251caf");
        System.out.println(ucSignature);*/
		//        JSONObject paramJson = new JSONObject();
        /*Map<String,String> paramJson=new HashMap<>();
        paramJson.put("user", "830901229");
        paramJson.put("orderid", "3621630481476640003");
        paramJson.put("gameorder", "1630481414573");
        paramJson.put("productid", "1");
        paramJson.put("total", "100");
        paramJson.put("roleid", "11");
        paramJson.put("serverid", "1");
        paramJson.put("time", "1630481680");
        paramJson.put("extension", "");
        paramJson.put("sign", "EB9C8590AE25FF118F1F06422F94B160");
        String resultStr = HttpUtils.doPost("http://h5-test.xnwan.com/api/v4/Sjda/pay", paramJson);
        System.out.println(resultStr);*/

        /*String gameId="2";
        String userName="830830218";
        String token="2-2-d214ad1d-da97-4cc0-b383-7ffe7a4aa36e";
        //        String sign = MD5.sign(userName+token+gameId,"ksy7458dsg5d4fg5rtgdf4g5","utf-8");
        //        String sign = SecurityUtils.getMD5Str(userName+token+gameId+"%Mo8uq!u3@M2$qFmqducl!sMfo2wcK2i");
        //        String sign ="8977f5ae0b3cb5d1c7f784ab712e14bd";
        String sign = MD5.sign(userName+token+gameId,"%Mo8uq!u3@M2$qFmqducl!sMfo2wcK2i","UTF-8");
        String param = "gameId=" + gameId + "&username=" + userName + "&token=" + token + "&sign=" + sign.toUpperCase();
        String resultStr = HttpUtil.httpGet("http://sdk.v3.test.3367.com/s/checkLogin", param);
        System.out.println(resultStr);*/

        /*String gameId = "2";
        String userName = "830907287";
        String pwd = "608980";
        String uuid = "b5f8447d-4ed5-4405-bf88-1be55a5496f2";
        String chl = "test";
        //        String sign = MD5.sign(userName+token+gameId,"ksy7458dsg5d4fg5rtgdf4g5","utf-8");
        //        String sign = SecurityUtils.getMD5Str(userName+token+gameId+"%Mo8uq!u3@M2$qFmqducl!sMfo2wcK2i");
        //        String sign ="8977f5ae0b3cb5d1c7f784ab712e14bd";
        String sign = Md5Utils.sign(userName + pwd + gameId, "%Mo8uq!u3@M2$qFmqducl!sMfo2wcK2i", "UTF-8");
        String param = "gameId=" + gameId + "&username=" + userName + "&pwd=" + pwd + "&uuid=" + uuid + "&chl=" + chl + "&sign=" + sign.toUpperCase();
        String resultStr = HttpUtils.sendGet("http://sdk.v3.test.3367.com/doLogin", param);
        System.out.println(resultStr);
        JSONObject resultJson = JSONObject.parseObject(resultStr);
        if (0 == resultJson.getIntValue("code")) {
            System.out.println(resultJson.getString("token"));
            System.out.println(resultJson.getJSONObject("data").getString("username"));
        }*/
	}
}
